<script setup>
import { ref, onMounted, inject, onBeforeUnmount } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const loading = inject('loading')
const pageHeight = ref('100%')
const download = ref({})
const isDownloading = ref(false)
const isFirstLaunch = route.query?.isFirstLaunch && route.query.isFirstLaunch === 'true'

// 取消更新 返回上一页
function cancelBack() {
  if (isFirstLaunch) {
    router.replace('/')
  } else {
    setTimeout(() => {
      router.go(-1)
    }, 600)
    ElMessage({
      message: '已经是最新版本啦~',
      type: 'success'
    })
  }
}

// 以下变量用于销毁监听事件
let updateAvailable = null
let downloadProgress = null
let updateDownloaded = null
let updateNotAvailable = null
let updateError = null

// 检查更新
app.sendMessage('check-update')
// 检测到新版本
updateAvailable = app.onMessage('update-available', () => {
  ElMessageBox.confirm('检测到新版本，是否立即更新？', '提示', {
    confirmButtonText: '更新',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 下载新版本
      app.sendMessage('update-app')
      isDownloading.value = true
      loading(false)
    })
    .catch(() => {
      // 取消更新
      cancelBack()
    })
})
// 下载进度
downloadProgress = app.onMessage('download-progress', (res) => {
  Object.assign(download.value, res)
})

// 新版本下载完成
updateDownloaded = app.onMessage('update-downloaded', () => {
  ElMessage({
    message: '新版本下载完成, 安装中...',
    type: 'success'
  })
})

// 无新版本
updateNotAvailable = app.onMessage('update-not-available', () => {
  cancelBack()
})
// 更新失败
updateError = app.onMessage('update-error', () => {
  ElMessage({
    message: '更新失败',
    type: 'error'
  })
  cancelBack()
})

onMounted(() => {
  pageHeight.value = document.querySelector('.main-box')?.clientHeight + 'px'
  loading(true)
})

onBeforeUnmount(() => {
  updateAvailable && updateAvailable()
  downloadProgress && downloadProgress()
  updateDownloaded && updateDownloaded()
  updateNotAvailable && updateNotAvailable()
  updateError && updateError()
  loading(false)
})
</script>

<template>
  <div class="flex flex-col items-center justify-center h-full m-4" :style="{ height: pageHeight }">
    <el-card v-if="isDownloading" class="w-full">
      <template #header>
        <div class="card-header">
          <span>下载中</span>
        </div>
      </template>
      <div>
        <el-progress
          :percentage="+download.percent || 0"
          :indeterminate="true"
          :format="(i) => i.toFixed(2) + '%'"
        />
      </div>
      <!-- <template #footer>
        <div class="flex items-center justify-center">
          <el-button type="info">取消更新</el-button>
        </div>
      </template> -->
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
